<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加任务</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%" height="740">
      <el-table-column label="任务ID" prop="id" align="center" width="50px"></el-table-column>
      <el-table-column label="日志类型" prop="cid_name" align="center" width="80px"></el-table-column>
      <el-table-column label="服务器范围" prop="s_name" align="center" width="150px"></el-table-column>
      <el-table-column label="时间范围" prop="level" align="center" width="180px">
        <template slot-scope="{ row }">
          {{ row.start_date }} -- {{ row.end_date }}
        </template>
      </el-table-column>
      <el-table-column label="筛选逻辑" align="center" width="80px">
        <template slot-scope="{ row }">
          {{ row.logic == 1 ? "且" : "或" }}
        </template>
      </el-table-column>
      <el-table-column label="筛选条件" width="250px">
        <template slot-scope="{ row }">
          <span v-for="(item, index) in row.condition" :key="index">
            <template v-if="
              item.field !== null &&
              item.field !== undefined &&
              item.field !== ''
            ">
              <el-tag effect="dark" class="elTag" type="success">{{
                getFields(row.cid)[item.field] || item.field
              }}</el-tag>
              <el-tag effect="dark" class="elTag" type="info">{{
                relations[item.relation]
              }}</el-tag>
              <el-tag v-if="!['min', 'max'].includes(item.relation)" effect="dark" class="elTag" type="danger">{{
                item.val }}</el-tag>
              <br>
            </template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="输出字段" width="250px">
        <template slot-scope="{ row }">
          <span v-for="(item, index) in row.result_condition" :key="index">
            <template v-if="
              item.field !== null &&
              item.field !== undefined &&
              item.field !== ''
            ">
              <el-tag effect="dark" class="elTag" type="success">{{
                getFields(row.cid)[item.field] || item.field
              }}</el-tag>
              <el-tag effect="dark" class="elTag" type="info">{{
                item.type == 1 ? "条件字段" : "汇总字段"
              }}</el-tag>
              <el-tag v-if="item.type == 2" effect="dark" class="elTag" type="danger">{{
                algorithms[item.algorithm]
              }}</el-tag>
              <br>
            </template>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" prop="create_user" align="center"></el-table-column>
      <el-table-column label="添加时间" prop="create_dt" align="center" width="150px"></el-table-column>
      <el-table-column label="状态" align="center" width="140px">
        <template slot-scope="{ row }">
          <span v-if="row.status === 0">未开始</span>
          <span v-else-if="row.status == 1">处理中</span>
          <span v-else-if="row.status == 2">已完成</span>
          <span v-else-if="row.status === 3" style="cursor: pointer;">
            <!-- Tooltip will show when hovering over the span element -->
            <el-tooltip :content="row.export_params.error || '无错误信息'" placement="left">
              <span>失败</span>
            </el-tooltip>
          </span>
          <span v-else-if="row.status == 4">已过期</span>
          <span v-else>未知状态</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <template v-if="row.status === 2">
            <el-button type="text" size="small" @click="handleDownload(row)">下载</el-button>
            <el-button type="text" size="small" @click="handleCopy(row)">复制</el-button>
          </template>
          <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="添加导出任务" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="服务器选择">
          <el-checkbox v-model="allServerChecked" @change="checkAllServer">显示全服</el-checkbox>
        </el-form-item>
        <div class="server-box">
          <ul class="menu-sub">
            <li v-for="(sgit, index) in serverGroups" :key="index">
              <el-checkbox v-model="sgit.flag" :indeterminate="itemIndeterminate(sgit)"
                @change="(val) => handleCheckAll(val, sgit)">{{ sgit.sgname }}</el-checkbox>
              <el-checkbox-group v-model="selectedData" style="padding-left: 30px" @change="handleChanges(sgit)">
                <el-checkbox v-for="sgits in sgit.children" :key="sgits.sid" :label="sgits.sid">{{ sgits.name
                }}</el-checkbox>
              </el-checkbox-group>
            </li>
          </ul>
        </div>
        <!-- <el-form-item label="服务器" prop="sid">
          <el-select v-model="dataForm.serverId" class="filter-item" filterable clearable placeholder="选择区服">
            <el-option v-for="item in serverList" :key="item.sid" :label="item.name+'('+item.sid+')'" :value="item.sid"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="日志类型" prop="cid">
          <el-select v-model="dataForm.cid" searchable clearable filterable placeholder="请选择类型" @change="typeChange">
            <el-option v-for="p in logTypeList" :key="p.id" :label="`${p.name}(${p.id})`" :value="p.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker v-model="dataForm.start_date" type="date" style="width: 27%" />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker v-model="dataForm.end_date" type="date" style="width: 27%" />
        </el-form-item>
        <el-form-item label="筛选逻辑" prop="logic">
          <el-select v-model="dataForm.logic" style="width: 120px" placeholder="请选择">
            <el-option label="且" :value="1"></el-option>
            <el-option label="或" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="筛选条件">
          <el-row>
            <el-col :md="3"><el-button type="primary" size="mini" class="add" icon="el-icon-plus"
                @click="conditionAdd">新增</el-button></el-col>
          </el-row>
          <el-row v-for="(item, index) in dataForm.condition" :key="index" class="mt-5" :gutter="12">
            <el-col :md="6">
              <el-select v-model="item.field" clearable filterable placeholder="请选择字段">
                <el-option v-for="(value, key) in fields" :key="key" :label="value" :value="key" />
              </el-select>
            </el-col>
            <el-col :md="6">
              <el-select v-model="item.relation" clearable filterable placeholder="请选择关系"
                @change="relationDisplay(item)">
                <el-option v-for="(value, key) in relations" :key="key" :label="value" :value="key" />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-if="item.valSelect" v-model="item.val" placeholder="数值" /></el-col>
            <el-col :md="4"><el-button type="danger" size="mini" icon="el-icon-delete"
                @click.prevent="removecondition(item)" /></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="导出结果">
          <el-row>
            <el-col :md="3"><el-button type="primary" size="mini" class="add" icon="el-icon-plus"
                @click="resultAdd">新增</el-button></el-col>
          </el-row>
          <el-row v-for="(item, index) in dataForm.result_condition" :key="index" class="mt-5" :gutter="12">
            <el-col :md="6">
              <el-select v-model="item.field" clearable filterable placeholder="请选择字段">
                <el-option v-for="(value, key) in fields" :key="key" :label="value" :value="key" />
              </el-select>
            </el-col>
            <el-col :md="6">
              <el-select v-model="item.type" clearable filterable placeholder="请选择字段类型"
                @change="algorithmDisplay(item)">
                <el-option key="1" label="条件字段" value="1" />
                <el-option key="2" label="汇总字段" value="2" />
              </el-select>
            </el-col>
            <el-col :md="6">
              <el-select v-if="item.showAlgorithmSelect" v-model="item.algorithm" clearable filterable
                placeholder="请选择字段算法">
                <el-option v-for="(value, key) in algorithms" :key="key" :label="value" :value="key" />
              </el-select>
            </el-col>
            <el-col :md="4"><el-button type="danger" size="mini" icon="el-icon-delete"
                @click.prevent="removeresult(item)" /></el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getServerListGroup } from '@/api/ops'
import { getServerList } from '@/api/ops'
import { deepClone } from '@/utils/index'
import {
  exportLogConfigList,
  handleBehaviorJob,
  getBehaviorJobList,
  deleteBehaviorJob,
  downlaodBehaviorLogJob,
  handleBehaviorJobStatus
} from '@/api/actorInfo'
// const defaultFormThead = ['server_id', 'player_id', 'player_name', 'player_level', 'player_vip', 'log_time', 'log_type', 'reason', 'data_1']
const defaultItem = {
  id: '',
  sid: [],
  cid: '',
  start_date: '',
  end_date: '',
  logic: 1,
  condition: [
    {
      field: '',
      relation: '',
      val: ''
    }
  ],
  result_condition: [
    {
      field: '',
      type: '',
      algorithm: ''
    }
  ]
}

export default {
  name: 'LogExport',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      list: [],
      dlist: [],
      actorList: [],
      serverList: [],
      multipleSelection: [],
      total: 0,
      listLoading: false,
      disabled: false,
      dataForm: deepClone(defaultItem),
      allServerChecked: false,
      selectedData: [],
      serverGroups: [],
      logTypeList: [],
      allFields: [],
      rules: {
        cid: [{ required: true, message: '请选择日志类型', trigger: 'change' }],
        start_date: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        end_date: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogVisible: false,
      fields: {},
      relations: {
        eq: '等于',
        gte: '大于等于',
        lte: '小于等于',
        min: '最小值',
        max: '最大值'
      },
      algorithms: {
        sum: '求和',
        avg: '平均值',
        count: '计数',
        max: '最大值',
        min: '最小值'
      }
    }
  },
  created() {
    this.getList()
    this.getServerList()
    this.getLogTypeList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = this.listQuery
      this.listLoading = true
      const res = await getBehaviorJobList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    async getServerList(params) {
      const query = params
      const res = await getServerList(query)
      this.serverList = res.data.items
      this.loading = false
    },
    handleBehaviorJobStatus(row, value, msg) {
      handleBehaviorJobStatus({ status: value }, row.id).then((response) => {
        this.getList()
        this.$message({
          type: 'success',
          message: msg
        })
      })
    },
    handleAdd() {
      this.handleAddData(deepClone(defaultItem))
      this.setSelectedDataAndSyncChecks([])
    },
    handleAddData(row) {
      // this.getLogTypeList()
      this.serverListGroup()
      this.dataForm = row
      this.dialogVisible = true
      console.log(this.dataForm)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    algorithmDisplay(item) {
      item.showAlgorithmSelect = item.type !== '1'
    },
    relationDisplay(item) {
      item.valSelect = !['min', 'max'].includes(item.relation)
    },
    typeChange(selectedValue) {
      console.log('当前选中的值:', selectedValue)
      this.fields = this.getFields(selectedValue)
    },
    getFields(selectedValue) {
      if (!this.allFields) {
        return []
      }
      if (selectedValue === 'actor') {
        return this.allFields.actor_fields
      } else {
        return this.allFields.behavior_fields
      }
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.sid = this.selectedData
          handleBehaviorJob(this.dataForm).then((response) => {
            if (response.status) {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deleteBehaviorJob({ id: row.id })
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch((err) => {
          console.error(err)
        })
    },
    handleCopy(row) {
      this.selectedData = row.sids
      this.handleAddData(row)
      this.setSelectedDataAndSyncChecks(row.sids)
    },
    handleDownload(row) {
      console.log(row)
      this.downloadLoading = true
      const url = row.export_params.url
      window.open(url, '_black')
      // import('@/vendor/Export2Excel').then((excel) => {
      //   let filterVal = []
      //   let tHeader = []
      //   console.log('点击下载')
      //   handleBehaviorJobStatus({ status: 1 }, row.id)
      //   downlaodBehaviorLogJob({ id: row.id, export: 1 })
      //     .then((response) => {
      //       this.dlist = response.data.items
      //       console.log('数据完成')
      //       if (response.data.items.length > 0) {
      //         filterVal = Object.keys(response.data.items[0])
      //         tHeader = filterVal.map((key) =>
      //           this.fields[key] !== undefined ? this.fields[key] : key
      //         )
      //       }

      //       const data = this.dlist.map((v) => filterVal.map((j) => v[j]))
      //       console.log('export_json_to_excel before')
      //       // 确保 export_json_to_excel 返回的是 Blob 对象
      //       const blob = excel.export_json_to_excel({
      //         header: tHeader,
      //         data,
      //         filename: '行为日志'
      //       })
      //       console.log(blob)
      //       console.log('export_json_to_excel after')
      //       // 如果返回的是 Blob 对象，则继续
      //       if (blob instanceof Blob) {
      //         const link = document.createElement('a')
      //         link.href = URL.createObjectURL(blob)
      //         link.download = '行为日志.xlsx'
      //         document.body.appendChild(link) // 确保链接添加到DOM中
      //         link.click()
      //         document.body.removeChild(link) // 下载完成后移除链接
      //         URL.revokeObjectURL(link.href)

      //         handleBehaviorJobStatus({ status: 2 }, row.id)
      //         // 文件下载完成后执行的逻辑
      //         this.$message({
      //           message: '文件下载成功',
      //           type: 'success'
      //         })
      //         this.downloadLoading = false
      //       } else {
      //         handleBehaviorJobStatus({ status: 2 }, row.id)
      //         console.error(
      //           'export_json_to_excel did not return a Blob object.'
      //         )
      //         this.$message({
      //           message: '文件下载失败，请稍后再试1',
      //           type: 'error'
      //         })
      //         this.downloadLoading = false
      //       }
      //     })
      //     .catch((error) => {
      //       handleBehaviorJobStatus({ status: 2 }, row.id)
      //       console.error('下载行为日志失败:', error)
      //       this.$message({
      //         message: '文件下载失败，请稍后再试2',
      //         type: 'error'
      //       })
      //       this.downloadLoading = false
      //     })
      // })
    },
    async getLogTypeList() {
      const res = await exportLogConfigList({})
      this.logTypeList = res.data.typeList
      this.allFields = res.data.fields
      this.loading = false
    },
    conditionAdd(row) {
      if (this.dataForm.condition.length === 6) {
        // return
      }
      this.dataForm.condition.push({
        field: '',
        relation: '',
        val: '',
        valSelect: true
      })
    },
    removecondition(row) {
      var index = this.dataForm.condition.indexOf(row)
      if (index !== -1) {
        this.dataForm.condition.splice(index, 1)
      }
    },
    resultAdd(row) {
      this.dataForm.result_condition.push({
        field: '',
        type: '',
        algorithm: ''
      })
    },
    removeresult(row) {
      var index = this.dataForm.result_condition.indexOf(row)
      if (index !== -1) {
        this.dataForm.result_condition.splice(index, 1)
      }
    },
    async serverListGroup(val) {
      getServerListGroup({ all: val }).then((res) => {
        this.serverGroups = res.data
      })
    },
    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map((item) => item.sid)
      const filterArr = this.selectedData.filter((v) => next.indexOf(v) === -1)
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map((ite) => ite.sid)
      return (
        infoLists.some((v) => this.selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => this.selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map((ite) => ite.sid)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
      console.log(this.serverGroups)
    },
    checkAllServer() {
      console.log('checkAllServer')
      this.serverListGroup(this.allServerChecked)
    },
    // 设置 selectedData 并自动勾选对应项
    setSelectedDataAndSyncChecks(newSelection) {
      this.selectedData = newSelection
      console.log(newSelection)
      for (const i in this.serverGroups) {
        for (const j in this.serverGroups[i].children) {
          if (newSelection.includes(this.serverGroups[i].children[j].sid)) {
            this.serverGroups[i].flag = true
          }
        }
        this.itemIndeterminate(this.serverGroups[i])
      }
      console.log(this.serverGroups)
      // this.$forceUpdate() // 强制更新视图以反映变化
    }
  }
}
</script>
<style>
.text30 {
  width: 30%;
}

.elTag {
  margin: 1px 2px;
}
</style>
